﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Dimok.Data.DataSources;
using Dimok.Web.UI;
using Data.DataSources;

public partial class Controls_Deferments : TableControl {
	Dimok.User.UserObject uox = new Dimok.User.UserObject();
	protected string Filter { 
		get {
			if (!IsPostBack && (Request["Filter"] + "") != "") return Request["Filter"] + "";
			return "[Total Principal]>1000";
		} 
	}
	protected string UserName = Dimok.User.UserObject.CurrentUserName;
	protected string UserDomain = Dimok.User.UserObject.CurrentUserDomain;
	protected string UserFullName = Dimok.User.UserObject.CurrentUserPath;
	string SelectFilterForProfile { get { return SelectFilter.ToUpper().Trim(); } }
	public string FilterUser {
		get {
			EnsureChildControls();
			return ddlUsers.SelectedValue == "" ? UserFullName : ddlUsers.SelectedValue;
		}
	}
	bool IsSelfFilter { get { return Profile.UserName.ToLower() == FilterUser.ToLower(); } }
	ProfileCommon FilterProfile {
		get {
			ProfileCommon pc = IsSelfFilter ? Profile : Profile.GetProfile(FilterUser);
			if (pc.Filters.Filter.PrimaryKey.Length == 0)
				pc.Filters.Filter.PrimaryKey = new DataColumn[] { pc.Filters.Filter.NameColumn, pc.Filters.Filter.PageTypeColumn };
			return pc;
		}
	}
	public string UsixID { get { return GridViewEx.SelectedDataKey == null ? "" : GridViewEx.SelectedDataKey["UsixID"] + ""; } }
	public int CompanyID { get { return GridViewEx.SelectedDataKey == null ? 0 : int.Parse("0"+GridViewEx.SelectedDataKey["CompanyID"]); } }
	public int LoanID { get { return GridViewEx.SelectedDataKey == null ? 0 : int.Parse("0"+GridViewEx.SelectedDataKey["LoanID"]); } }
	private Profiler profileLib;
	private string SortExpression { get {return  ViewState["SortExpression"] + ""; } set { ViewState["SortExpression"] = value; } }
	Dimok.ArrayListEx ColumnsTotal = new Dimok.ArrayListEx(new string[] { "total principal"});
	Dimok.ArrayListEx ColumnsAverage = new Dimok.ArrayListEx(new string[] { "dpd", "dslp"  });

	private static Dimok.Data.ADsUser.th_AdsUserDataTable _users = null;

	public Dimok.Data.ADsUser.th_AdsUserDataTable GetUsers() {
		if (_users == null) {
			Data.DataSources.UsersDataSource dsoUsers = new Data.DataSources.UsersDataSource();
			dsoUsers.ShowProfiles = true;
			_users = dsoUsers.SelectEx();
		}
		return _users;
	}

	#region State
	protected override void SetStateValues(Hashtable values) {
		base.SetStateValues(values);
		//FilterQueue = values[ClientID + "FilterQueue"] + "";
	}
	protected override void GetStateValues(Hashtable values) {
		base.GetStateValues(values);
		//values[ClientID + "FilterQueue"] = FilterQueue;
	}
	#endregion

	protected override void OnLoad(EventArgs e) {
		base.OnLoad(e);
		dsUsersCached.TypeName = this.GetType().AssemblyQualifiedName;
		GridViewEx = grv;
		ObjectDS = ds;
		if (!IsPostBack && !ScriptManager.GetCurrent(Page).IsInAsyncPostBack) {
			try {
				ddlFontSize.SelectedValue = profileLib.Page.FontSize + "";
			} catch { }
		}
	}

	protected override void OnInit(EventArgs e) {
		base.OnInit(e);
		profileLib = new Profiler(Profile, Page, this);

		btnSaveFilter.Command += new CommandEventHandler(USIXExportList_Command);
		btnDeleteFilter.Command += new CommandEventHandler(USIXExportList_Command);
		btnExcel.Command += new CommandEventHandler(btnExcel_Command);

		ddlFontSize.SelectedIndexChanged += new EventHandler(ddlFontSize_SelectedIndexChanged);

		ds.Selected += new ObjectDataSourceStatusEventHandler(ds_Selected);
		if (!IsPostBack && !ScriptManager.GetCurrent(Page).IsInAsyncPostBack) {
			SelectFilter = Filter;
			txtDateSince.Text = DateTime.Now.AddMonths(-12).ToString("MM/dd/yyyy");
		}
	}

	protected void grv_SearchChanged(string search) {
		SetCaption(SelectFilterForProfile);
	}

	protected override void Render(HtmlTextWriter writer) {
		if (grv.AllowPaging) {
			base.Render(writer);
			return;
		}
		Response.Clear();
		Response.AddHeader("content-disposition", "attachment; filename="+(ddlFilters.SelectedItem.Text==""?"Deferments":ddlFilters.SelectedItem.Text)+".xls");
		Response.Charset = "";
		// If you want the option to open the Excel file without saving than
		// comment out the line below
		// Response.Cache.SetCacheability(HttpCacheability.NoCache);
		Response.ContentType = "application/vnd.xls";
		System.IO.StringWriter stringWrite = new System.IO.StringWriter();
		System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
		grv.RenderControl(htmlWrite);
		Response.Write(stringWrite.ToString());
		Response.End();
	}
	void btnExcel_Command(object sender, CommandEventArgs e) {
		grv.RequiresDataBinding = true;
		grv.AllowPaging = false;
		grv.AllowSorting = false;
		grv.ShowSearch = false;
		SetCaption("");
	}
	protected void USIXExportList_Command(object sender, CommandEventArgs e) {
		GridFilterDS.FilterRow r;
		ProfileCommon p = hdnFilterUser.Value == "" ? FilterProfile : Profile.GetProfile(Lib.GetUserFullName(hdnFilterUser.Value));
		switch (e.CommandName) {
			case "Import":
				Data.SQL.ExecuteSP("usix.s_Export", (e.CommandArgument + "").Split(','));
				break;
			case "SaveFilter":
				//if (p.UserName != Profile.UserName && !uox.IsAdmin) throw new NotSupportedException("Sorry. You are not authorized to save filter for other user.");
				if (hdnFilterName.Value == "null") hdnFilterName.Value = "";
				r = p.Filters.Filter.FindByNamePageType(hdnFilterName.Value,PageBase.FilterPageType(this));
				if (r != null) {
					r.Value = SelectFilterForProfile;
					r.HideColumns = grv.HideColumns;
					r.SortExpression = grv.SortExpression;
				} else p.Filters.Filter.AddFilterRow(hdnFilterName.Value + "", hdnFilterName.Value == "" ? "" : SelectFilterForProfile, grv.HideColumns, grv.SortExpression, Page.GetType().Name);
				p.Filters.AcceptChanges();
				p.Save();
				ddlFilters.DataBind();
				break;
			case "DeleteFilter":
				if (FilterUser.ToLower() != Profile.UserName.ToLower() && !uox.IsAdmin) throw new NotSupportedException("Sorry. " + Profile.UserName + " is not an owner of " + FilterUser + ".");
				r = p.Filters.Filter.FindByNamePageType(e.CommandArgument + "", PageBase.FilterPageType(this));
				if (r != null) {
					r.Delete();
					p.Filters.AcceptChanges();
					p.Save();
					ddlFilters.ClearSelection();
					ddlFilters.DataBind();
				}
				break;
			//System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>(Profile.Filters);
			//if( .Contains(SelectFilter)){
			//  Profile.Filters
			default: throw new NotImplementedException(e.CommandName + " is not implemented");
		}
	}

	void ds_Selected(object sender, ObjectDataSourceStatusEventArgs e) {
		System.Data.DataView dv = e.ReturnValue as System.Data.DataView;
		if (dv != null && dv.Count == 1 && dv[0][0] != DBNull.Value)
			grv.SelectedIndex = 0;
		if (dv == null || dv.Count < 2) return;
		grv.HeaderTotals = dv.Table.Clone();
		System.Data.DataRow rowSum = grv.HeaderTotals.NewRow();
		foreach (System.Data.DataColumn column in dv.Table.Columns)
			rowSum[column.ColumnName] = ColumnsTotal.Contains(column.ColumnName.ToLower()) ?
				string.Format("{0:n}", GridViewEx.GetColumnTotal(dv.Table.Rows, column.ColumnName)) : " ";
		System.Data.DataRow rowAvg = grv.HeaderTotals.NewRow();
		grv.HeaderTotals.Rows.InsertAt(rowSum, 0);
	}

	protected void ddlFilters_PreRender(object sender, EventArgs e) {
		try {
			if (ddlFilters.Items.FindByValue(SelectFilterForProfile) != null &&
				ddlFilters.SelectedValue != SelectFilterForProfile)
				ddlFilters.SelectedValue = SelectFilterForProfile;
			if (!IsPostBack) ScriptLocal(sender);
		} catch { }
		if (ddlFilters.SelectedIndex >= 0) btnDeleteFilter.CommandArgument = ddlFilters.SelectedItem.Text;
		btnDeleteFilter.Visible = ddlFilters.SelectedIndex > 1;
	}

	protected void ddlFilters_SelectedIndexChanged(object sender, EventArgs e) {
		SelectFilter = ddlFilters.SelectedItem.Value.Trim();
		string filterName = ddlFilters.SelectedIndex < 0 ? "" : Regex.Replace(ddlFilters.SelectedItem.Text, @"\{.+\}$", "");
		GridFilterDS.FilterDataTable dtFilter = FilterProfile.Filters.Filter;
		GridFilterDS.FilterRow rowFilter = dtFilter.FindByNamePageType(filterName, PageBase.FilterPageType(this));
		if (rowFilter == null || rowFilter.HideColumns == "")
			rowFilter = Profile.Filters.Filter.FindByNamePageType("", PageBase.FilterPageType(this));
		if (rowFilter != null && rowFilter.HideColumns != "")
			grv.HideColumns = rowFilter.HideColumns;
		SetFilterBoxes(SelectFilter);
		grv.RequiresDataBinding = true;
		SetCaption(SelectFilterForProfile);
		//btnDeleteFilter.Visible = ddlFilters.SelectedIndex > 1;
	}
	protected void ddlUsers_SelectedIndexChanged(object sender, EventArgs e) {
		ddlFilters.SelectedValue = "";
		ddlFilters.DataBind();
	}

	protected void ddlUsers_DataBound(object sender, EventArgs e) {
		if (!IsPostBack) {
			ddlUsers.SelectedValue = Dimok.User.UserObject.CurrentUserPath.ToLower();
			ScriptLocal(sender);
		}
	}

	//void ds_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) {
	//	ds.Where.Add(Filter);
	//	pnlFilter.InnerHtml = Filter;
	//	ds.OrderBys = SortExpression;
	//}

	//void grv_RowUpdated(object sender, GridViewUpdatedEventArgs e) {
	//  RefreshNotesCache();
	//  grv.RequiresDataBinding = true;
	//}

	void ddlFontSize_SelectedIndexChanged(object sender, EventArgs e) {
		profileLib.Page.FontSize = ((ListControl)sender).SelectedValue;
		profileLib.Save();
	}
	void SetCaption(string Caption) {
		lblCaption.Text = Caption;
	}


	protected string ShowApplicantJS(object applID) { return "event.cancelBubble = true;if(!event.ctrlKey)showApplInfo(" + applID + ")"; }
}
